package com.mano.mall.gateway.handler.impl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.mano.mall.common.base.BaseResponse;
import com.mano.mall.common.constants.Constants;
import com.mano.mall.gateway.feign.AuthorizationServiceFeign;
import com.mano.mall.gateway.handler.GatewayHandler;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.netflix.zuul.context.RequestContext;

import lombok.extern.slf4j.Slf4j;

/**
 * 验证Token
 */
@Component
@Slf4j
public class ApiCheckTokenHandler extends BaseHandler implements GatewayHandler {

	@Autowired
	private AuthorizationServiceFeign verificaCodeServiceFeign;

	@Override
	public void service(RequestContext ctx, HttpServletRequest request, HttpServletResponse response) {
		log.info("<<<<流程3判断 API验证Token>>>>>>>>");
		String servletPath = request.getServletPath();
		log.info(">>>>>servletPath:" + servletPath + ",servletPath.substring(0, 5):" + servletPath.substring(0, 5));
		// 只有对外开放的接口才有 校验 access_token
		if (!servletPath.substring(0, 7).equals("/public")) {
			return ;
		}

		String accessToken = request.getParameter("accessToken");
		log.info(">>>>>accessToken验证:" + accessToken);
		if (StringUtils.isEmpty(accessToken)) {
			resultError(Constants.HTTP_NOT_AUTH,ctx, "AccessToken cannot be empty");
			return ;
		}
		// 调用接口验证accessToken是否失效
		BaseResponse<JSONObject> appInfo = verificaCodeServiceFeign.getAppInfo(accessToken);
		log.info(">>>>>>data:" + appInfo.toString());
		if (!isSuccess(appInfo)) {
			resultError(Constants.HTTP_NO_ACCESS_TOKEN,ctx, appInfo.getMsg());
			return ;
		}
	}

}
